/**
 * 
 */
package org.mule.transport.jpa;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.text.StrTokenizer;

/**
 * @author alvarezjm
 * 
 */
public class JpaContainer<T extends Comparable<T>> {

	private String fieldId; // example "id"

	private T value; // example new Long(100) T is a Long

	private String operation; // example ">"

	public String getFieldId() {
		return fieldId;
	}

	public void setFieldId(String fieldId) {
		this.fieldId = fieldId;
	}

	public T getValue() {
		return value;
	}

	public void setValue(T value) {
		this.value = value;
	}

	public String getOperation() {
		return operation;
	}

	public void setOperation(String operation) {
		this.operation = operation;
	}

	@Override
	public String toString() {
		return new ToStringBuilder(this).append("field", fieldId).append("operation", operation).append("value", value).toString();
	}

	public <R> Predicate toPredicate(CriteriaBuilder cb, Root<R> root) {
		Path<T> path;
		if (fieldId.contains(".")) {
			StrTokenizer tokenizer = new StrTokenizer(fieldId, ".");
			path = root.<T> get(tokenizer.getTokenArray()[0]);
			for (int i = 1; i < tokenizer.getTokenArray().length; i++) {
				path = path.<T> get(tokenizer.getTokenArray()[i]);
			}
		} else {
			path = root.<T> get(fieldId);
		}
		if (">".equals(operation)) {
			return cb.greaterThan(path, value);
		} else if ("<".equals(operation)) {
			return cb.lessThan(path, value);
		} else if ("<=".equals(operation)) {
			return cb.lessThanOrEqualTo(path, value);
		} else if (">=".equals(operation)) {
			return cb.greaterThanOrEqualTo(path, value);
		} else {
			return cb.equal(path, value);
		}
	}
}
